package com.tarena.lbs.business.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.mapper.BusinessMapper;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class BusinessRepositoryImpl implements BusinessRepository {

    private BusinessMapper businessMapper;

    @Autowired
    public void setBusinessMapper(BusinessMapper businessMapper) {
        this.businessMapper = businessMapper;
    }

    public PageResult<BusinessVO> pageList(BusinessQuery query) {
        QueryWrapper<BusinessPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(query.getBusinessName() != null, "business_name", query.getBusinessName());
        queryWrapper.eq(query.getBusinessStatus() != null, "business_status", query.getBusinessStatus());
        queryWrapper.eq(query.getBusinessHeadPhone() != null, "business_head_name",query.getBusinessHeadPhone());
        queryWrapper.ge(query.getStartingTime() != null, "entry_time",query.getStartingTime());
        queryWrapper.le(query.getEndTime() != null, "entry_time",query.getEndTime());
        List<BusinessPO> list = businessMapper.selectList(queryWrapper);
        // 将 List<BusinessPO> 转换为 List<BusinessVO>
        List<BusinessVO> voList = list.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        Long total = businessMapper.selectCount(queryWrapper);
        PageResult<BusinessVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setObjects(voList);
        pageResult.setPageNo(query.getPageNo());
        pageResult.setPageSize(query.getPageSize());
        return pageResult;
    }

    /**
     * 将 BusinessPO 对象转换为 BusinessVO 对象
     * @param po BusinessPO 对象
     * @return BusinessVO 对象
     */
    private BusinessVO convertToVO(BusinessPO po) {
        BusinessVO vo = new BusinessVO();
        BeanUtils.copyProperties(po, vo);
        return vo;
    }

    public void save(BusinessParam param) {
        BusinessPO po = new BusinessPO();
        BeanUtils.copyProperties(param, po);
        po.setEntryTime(new Date());
        businessMapper.insert(po);
    }

    public BusinessPO businessStoreDetail(Integer businessId) {
        return businessMapper.selectById(businessId);
    }
}
